import { onMounted, onUnmounted, Ref } from 'vue'
import './slide-in-text.scss'
/**
 * 一个字一个字滑下来的效果
 */
type Direction = 'left' | 'right' | 'top' | 'bottom'

export function createSlideInText(dom: Ref<HTMLElement | null>, duration:any, direction?: Direction) {
  let s: SlideInText 
  onMounted(() => {
     if(dom.value) {
      s = new SlideInText(dom.value, duration, direction)
      s.start()
    }

  })
  onUnmounted(() => {
    if (s) {
      s.destroy()
    }
  })
}


 

class SlideInText {
    private direction: Direction = 'bottom'
    private text: string 
    private container: HTMLElement
    private duration: number
    private timer?: number
    constructor(dom: HTMLElement,  duration:number, direction: Direction = 'bottom') {
     this.container = dom
     this.direction = direction
     this.text = this.container.innerText
     this.duration = duration
    }

    destroy() {
        clearInterval(this.timer)
      }


     start() {

        this.container.innerHTML = ''
        let index = 0
        this.timer = setInterval(() => {
          if (index >= this.text.length) {
            clearInterval(this.timer)
            return
          }
          let currentChart = this.text[index++]
          let span = document.createElement('span')
          span.innerHTML = currentChart
          span.classList.add('slide-from-' + this.direction)
          this.container.appendChild(span)
        }, this.duration / this.text.length)



     }


}

 